﻿using Demo.PetaPoco.Application.Services.User;
using Microsoft.Extensions.Logging;
using PmSoft.Core.EventBus;
using PmSoft.Data.Abstractions.Events;

namespace Demo.PetaPoco.Application.Events;

internal class EntityAddedEventHandler : IAsyncEventHandler<EntityAddedEventArgs>
{
	private readonly ILogger _logger;
	private readonly IEventBus _eventBus;
	private readonly UserService _userService;
	public EntityAddedEventHandler(ILogger<EntityUpdatedEventHandler> logger, IEventBus eventBus,
		UserService userService)
	{
		_logger = logger;
		_eventBus = eventBus;
		_userService = userService;
	}
	public Task HandleAsync(EntityAddedEventArgs eventArgs)
	{
		//await Task.Run(() => throw new Exception("测试事件抛出异常"));
		//await Task.Delay(15000);
		//var user = await _userService.GetUserAsync((int)eventArgs.EntityId);
		_logger.LogDebug($"添加实体 审计组[{eventArgs.AuditableAttribute.GroupName}] 表描述[{eventArgs.EntityDescription}] 表名[{eventArgs.TableName}] 实体ID[{eventArgs.Entity.Id}]");
		//_eventBus.Publish(eventArgs);

		//for (int i = 0; i < 10; i++)
		//{
		//	_eventBus.FireAndForget(new UserCreatedEventArgs { });
		//}
		return Task.CompletedTask;
	}
}

internal class EntityUpdatedEventHandler : IAsyncEventHandler<EntityUpdatedEventArgs>
{
	private readonly ILogger _logger;
	private readonly IEventBus _eventBus;
	public EntityUpdatedEventHandler(ILogger<EntityUpdatedEventHandler> logger, IEventBus eventBus)
	{
		_logger = logger;
		_eventBus = eventBus;
	}
	public Task HandleAsync(EntityUpdatedEventArgs eventArgs)
	{
		string changedProperties = string.Join("|", eventArgs.ChangedProperties.Select(m => $"[{m.PropertyName}] “{m.OldValue}” to “{m.NewValue}”"));
		_logger.LogDebug($"更新实体 审计组[{eventArgs.AuditableAttribute.GroupName}] 表描述[{eventArgs.EntityDescription}] 表名[{eventArgs.TableName}] 实体ID[{eventArgs.EntityId}] 更改属性={changedProperties}");
		return Task.CompletedTask;
	}
}

internal class EntityDeletedEventHandler : IAsyncEventHandler<EntityDeletedEventArgs>
{
	private readonly ILogger _logger;
	public EntityDeletedEventHandler(ILogger<EntityUpdatedEventHandler> logger)
	{
		_logger = logger;
	}
	public Task HandleAsync(EntityDeletedEventArgs eventArgs)
	{
		_logger.LogDebug($"删除实体 审计组[{eventArgs.AuditableAttribute.GroupName}] 表描述[{eventArgs.EntityDescription}] 表名[{eventArgs.TableName}] 实体ID[{eventArgs.EntityId}]");
		return Task.CompletedTask;
	}
}

